package com.water_work_form.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.water_work_form.entity.RecordDrugConsume;
import com.water_work_form.mapper.*;
import com.water_work_form.service.RecordDrugConsumeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 记录——在线仪表药剂领用登记表 服务实现类
 * </p>
 *
 * @author xuke
 * @since 2023-09-14
 */
@Service
public class RecordDrugConsumeServiceImpl extends ServiceImpl<RecordDrugConsumeMapper, RecordDrugConsume> implements RecordDrugConsumeService {

    @Autowired
    RecordDrugConsumeMapper recordDrugConsumeMapper;

    @Autowired
    BasicFormMapper basicFormMapper;

    @Value("${file.templateFilePath}")
    private String templateFilePath;

    @Value("${file.destFilePath}")
    private String destFilePath;

    /**
     * 记录——在线仪表药剂领用登记表 项目查询
     * @param deviceName 仪器名称（device_name）若非空匹配查询
     * @param drugName 药剂名称（drug_name）若非空匹配查询
     * @param status 状态（status）若非空匹配查询
     * @param current 分页 当前页
     * @param size 分页 每页最大数据量
     * @return 返回相应数据 按照状态（status）、领用日期（consume_date）的顺序进行升序排序
     */
    @Override
    public IPage<RecordDrugConsume> selectRecordDrugConsume(String deviceName, String drugName, String status, Integer current, Integer size){
        QueryWrapper<RecordDrugConsume> queryWrapper = new QueryWrapper<>();
        if(!deviceName.isEmpty()){
            queryWrapper.eq("device_name", deviceName);
        }
        if(!status.isEmpty()){
            queryWrapper.eq("status", status);
        }
        if(!drugName.isEmpty()){
            queryWrapper.eq("drug_name", drugName);
        }
        queryWrapper.orderByAsc("status", "consume_date");
        IPage<RecordDrugConsume> page = new Page<>(current, size);
        return this.page(page, queryWrapper);
    }

    /**
     * 记录——在线仪表药剂领用登记表 项目查询
     * @param deviceName 仪器名称（device_name）若非空匹配查询
     * @param drugName 药剂名称（drug_name）若非空匹配查询
     * @return 返回相应数据 领用日期（consume_date）的顺序进行升序排序
     */
    @Override
    public List<RecordDrugConsume> listRecordDrugConsume(String deviceName, String drugName){
        QueryWrapper<RecordDrugConsume> queryWrapper = new QueryWrapper<>();
        if(!deviceName.isEmpty()){
            queryWrapper.eq("device_name", deviceName);
        }
        if(!drugName.isEmpty()){
            queryWrapper.eq("drug_name", drugName);
        }
        queryWrapper.orderByAsc("consume_date");
        return recordDrugConsumeMapper.selectList(queryWrapper);
    }

    /**
     * 记录——在线仪表药剂领用登记表 基础表数据查询
     * @param name form表name
     * @return 返回相应数据 表名为键名
     */
    @Override
    public Map<String,Object> selectBasicDrugConsume(String name) {
        Map<String,Object> map = new HashMap<>();
        map.put("form", basicFormMapper.getOneByName(name));
        return map;
    }

    /**
     * 记录——在线仪表药剂领用登记表 列表数据导出
     * @param recordDrugConsumeList 需要导出的数据列表
     * @param deviceName 在线仪表名称
     * @param drugName 药剂名称
     * @throws IOException 异常
     */
    @Override
    public void downloadRecordDrugConsume(List<RecordDrugConsume> recordDrugConsumeList, String deviceName, String drugName) throws IOException {
        Map<String, Object> data = new HashMap<String, Object>();
        List<String> formatConsumeDate  = new ArrayList<>();
        List<String> formatEffectiveDate  = new ArrayList<>();
        List<Map<String,Object>> formatList = new ArrayList<Map<String,Object>>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        formatConsumeDate  = recordDrugConsumeList.stream()
                .map(recordDrugConsume -> dateFormat.format(recordDrugConsume.getConsumeDate()))
                .collect(Collectors.toList());
        formatEffectiveDate  = recordDrugConsumeList.stream()
                .map(recordDrugConsume -> dateFormat.format(recordDrugConsume.getEffectiveDate()))
                .collect(Collectors.toList());
        for (int i = 0;i < recordDrugConsumeList.size();i++){
            Map<String,Object> map = new HashMap<>();
            map.put("consumeQuantity",recordDrugConsumeList.get(i).getConsumeQuantity());
            map.put("residueQuantity",recordDrugConsumeList.get(i).getResidueQuantity());
            map.put("userName",recordDrugConsumeList.get(i).getUserName());
            map.put("consumeDate",formatConsumeDate.get(i));
            map.put("effectiveDate",formatEffectiveDate.get(i));
            formatList.add(map);
        }
        data.put("lists",formatList);
        data.put("deviceName",deviceName);
        data.put("drugName",drugName);
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder()
                .bind("lists", policy).build();
        XWPFTemplate compile = XWPFTemplate.compile(templateFilePath + "RecordDrugConsume.docx",config);
        compile.render(data);
        compile.writeToFile(destFilePath + "out_recordDrugConsume.docx");
        compile.close();
    }


}
